<template>
  <div>
    <el-dialog :title="title + '身份'" :visible.sync="dialogVisible" :before-close="close" :close-on-click-modal="false" width="40%">
    <el-form :rules="rules" :model="form" ref="thisRef" hide-required-asterisk label-width="80px" label-position='left'>
        <el-form-item label="名称 :" prop="name">
            <el-input v-model="form.name" maxlength="8"></el-input>
        </el-form-item>
        <el-form-item label="描述 :" prop="desc">
            <el-input type="textarea" v-model="form.desc" maxlength="200"  :rows="3" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="权限 :">
            <el-tree
            ref="tree"
            :check-strictly="false"
            :data="form.routes"
            :props="defaultProps"
            show-checkbox
            node-key="path">
            </el-tree>
        </el-form-item>
    </el-form>
     <span slot="footer" class="dialog-footer">
        <el-button @click="close()" :loading="buttonLoading">取 消</el-button>
        <el-button type="primary" @click="add()" :loading="buttonLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 生成树状图仅用处理过的title  传参时提交所有
import path from 'path'
import {addrole,updaterole} from '@/api/auth'
export default {
 data() {
    return {
      title:'新增',
      dialogVisible: false,
      buttonLoading: false,
      form:{
        name: '',
        desc: '',
        routes: []
      },
      rules: {
        name: [{ required: true, message: "请填写身份名称", trigger: "blur" }],
        desc: [{ required: true, message: "请填写身份描述", trigger: "blur" }],
      },
      defaultProps: {
        children: "children",
        label: "title",
      },
      asyncRoute:[],
      curId: '',
    };
  },
  methods:{
    //打开
    open(asyncRouterMap,data) {
      console.log(asyncRouterMap,'asyncRouterMap')
      this.asyncRoute = asyncRouterMap
    //   console.log(this.asyncRoute,'iuasdiuaiud')
      const routes = this.generateRoute(asyncRouterMap)
      console.log(routes,'routes')
      this.form.routes = routes
      if(data){
          this.title = '编辑'
          this.edit(data)
      }
      this.dialogVisible = true;
    },
    //关闭
    close() {
      this.dialogVisible = false;
      this.$refs.thisRef.resetFields();
      this.form = {
        name: '',
        desc: '',
        routes: []
      },
      this.title = '新增',
      this.curId = ''
    },
    //将路由数据转化格式
    generateRoute(routes, basePath = '/'){
        const res = []
        // console.log(routes,'sss')
        // for (x of xxx){ }  遍历所有项
        for (const route of routes) {
            //有 hidden 跳过
           if(route.hidden) { continue } 
           // 原理同side渲染 判断子集数量
           const onlyOneShowingChild = this.onlyOneShowingChild(route.children,route)
           // 转化children后，若只有一个显示则进入数组
           if(route.children && onlyOneShowingChild){
               route = onlyOneShowingChild
           }
           
           const data = {
               path: path.resolve(basePath,route.path),
               title: route.meta && route.meta.title
           }

           if(route.children) {
               //若有children 再进函数，拼接的basePath路由改为本身
               data.children = this.generateRoute(route.children,data.path)
           }

           res.push(data)
        }

        return res
    },
    onlyOneShowingChild(children = [], parent){
        let onlyOneChild = null
        //过滤子路由含有hidden的
        const showingChildren = children.filter(item => !item.hidden)
        
        if(showingChildren.length === 1){
            //子集只有一个:显示子集，路由拼接
            onlyOneChild = showingChildren[0]
            onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
            return onlyOneChild
        }

        if(showingChildren.length === 0){
            //没有子集，显示父级本身
            onlyOneChild = { ...parent,path: '',noShowingChildren: true }
            return onlyOneChild
        }

        return
    },
    generateTree(routes, basePath = '/', checkedKeys){
        const res = []

        for (const route of routes){

            const routePath = path.resolve(basePath,route.path)

            if(route.children) {
                route.children = this.generateTree(route.children,routePath,checkedKeys)
            }
            
            //includes方法：查询数组中是否包含某项  或有children
            if(checkedKeys.includes(routePath)|| (route.children && route.children.length >= 1)) {
                res.push(route)
            }
        }
        return res
    },
    generateArr(routes) {
        console.log(routes,'routesroutesroutes')
        let data = []
        routes.forEach(route => {
            data.push(route)
            //有子去循环
            if(route.children){
                const temp = this.generateArr(route.children)
                //将所有展开，暴露出节点供选择
                if(temp.length > 0){
                    data = [...data,...temp]
                }
            }
        });
        return data
    },
    add(){
        this.$refs.thisRef.validate( async valid => {
            if(!valid) return
            //获取选中的节点
            this.buttonLoading = true
            const checkedKeys = this.$refs.tree.getCheckedKeys()
            console.log(checkedKeys,'checkedKeys')
            //将所有转化后的数据发给后端，包括hidden,原理同初始化树状图数据
            const deepRoute = JSON.parse(JSON.stringify(this.asyncRoute))
            this.form.routes = this.generateTree(deepRoute, '/', checkedKeys)
            console.log(this.form,'arr')
            // return
            if(this.title === '编辑'){
                console.log('编辑',this.curId,this.form)
                updaterole(this.curId,this.form)
                    .then(res => {
                        console.log(res,'编辑res')
                        if(res && res.status === 200){
                            this.$message.success('编辑成功！')
                            this.buttonLoading = false
                            this.$emit('refsh')
                        }
                        this.close()
                    })
                    .catch(()=>{
                        this.$message.error('编辑失败！')
                        this.buttonLoading = false
                    })
                return
            }else{
                addrole(this.form)
                .then(res=>{
                    console.log(res,7777777)
                    if(res && res.status === 200){
                        this.$message.success('添加成功！')
                        this.buttonLoading = false
                        this.$emit('refsh')
                    }
                    this.close()
                })
                .catch(()=>{
                    this.$message.error('添加失败！')
                    this.buttonLoading = false
                })
            }  
        })
    },
    edit(data){
        console.log(data,'curdata')
        const {name,desc,routes,_id} = data
        this.form.name = name
        this.form.desc = desc
        this.curId = _id
        this.$nextTick(() => {
            //转化格式
            const genRoutes = this.generateRoute(routes)
            const nodes = this.generateArr(genRoutes)
            console.log(nodes,'sss')
            //通过节点选择（label）  https://element.eleme.cn/#/zh-CN/component/tree
            this.$refs.tree.setCheckedNodes(nodes)
        })
    }
  },
};
</script>

<style lang="scss" scoped>
</style>